import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/dao/TencenNewFriendsDao.dart';
import 'package:changxindianzishangwu/model/friend_applist.dart';
import 'package:changxindianzishangwu/pages/contacts/user_add_info_page.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class AddUserPage extends StatefulWidget {
  String userId;
  AddUserPage({Key key, this.userId}) : super(key: key);

  @override
  _AddUserPageState createState() => _AddUserPageState();
}

class _AddUserPageState extends State<AddUserPage> {
  var packageName = "AddUserPage";
  V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
  List<V2TimFriendInfoResult> friendInfoResult;
  @override
  void initState() {
    super.initState();

    //_getUserInfoData();
    ready();
    _getFriendsApp();
  }

  ready() async {
    await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .setFriendApplicationRead();
  }

  List<Widget> dataList = [];
  V2TimValueCallback<List<V2TimFriendInfoResult>> userEntity;
  V2TimUserFullInfo _userEntity;
  List<String> userId;
  _getUserInfoData() async {
    userId = [];
    if (list.data.friendApplicationList.length > 0) {
      list.data.friendApplicationList.forEach((element) {
        userId.add(element.userID);
        print("=========" + element.userID);
      });

      userId.forEach((element) {
        print("=========2" + element);
      });
      userEntity = await timManager.v2TIMFriendshipManager
          .getFriendsInfo(userIDList: userId);
      friendInfoResult = userEntity.data;
      await _getData();
    } else {
      await _getData();
    }
  }

  V2TimValueCallback<V2TimFriendApplicationResult> list;

  _getFriendsApp() async {
    list = await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .getFriendApplicationList();

    ///已过期
    // list.data.friendApplicationList.forEach((element) {
    //   if (element.addTime ==
    //       DateTime.now().millisecondsSinceEpoch - 86400000 * 3) {
    //     TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
    //         .deleteFriendApplication(type: 1, userID: element.userID);
    //     TencenNewFirendsDao.addInfo(
    //         element.addWording,
    //         element.addTime.toString(),
    //         DateTime.now().millisecondsSinceEpoch.toString(),
    //         "3",
    //         element.userID,
    //         widget.userId);
    //   }
    // });
    await _getUserInfoData();
  }

  _getData() async {
    dataList = [];
    dataList.add(InkWell(
      onTap: () {
        // dev.log(packageName + "搜索聊天记录跳转");
        //Get.to(() => SearchUserPage());
        Get.toNamed("/searchUserIdPage");
      },
      child: Container(
        color: Colors.white,
        child: Container(
            height: ScreenUtil().setHeight(32),
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: 20),
            margin: EdgeInsets.only(
                left: ScreenUtil().setWidth(10),
                top: ScreenUtil().setHeight(10),
                right: ScreenUtil().setWidth(15)),
            decoration: BoxDecoration(
                color: Color.fromRGBO(241, 241, 241, 1),
                borderRadius: BorderRadius.circular(6)),
            child: Text(
              "手机号/用户ID",
              style: TextStyle(
                  fontSize: 15, color: Color.fromRGBO(153, 153, 153, 1)),
            )),
      ),
    ));
    dataList.add(Container(
      margin: EdgeInsets.only(top: 14),
      padding: EdgeInsets.only(left: 15.w),
      height: 30,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: ZdColor.rgba(241, 241, 241, 1),
      ),
      child: Text(
        "待处理",
        style:
            TextStyle(fontSize: sp(12), color: ZdColor.rgba(153, 153, 153, 1)),
      ),
    ));

    for (int i = 0; i < list.data.friendApplicationList.length; i++) {
      if (list.data.friendApplicationList[i].type == 1) {
        dataList.add(ListTile(
          leading: Container(
              height: width(40),
              width: width(40),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  color: Colors.greenAccent,
                  image: list.data.friendApplicationList[i].faceUrl == null
                      ? DecorationImage(
                          image: CachedNetworkImageProvider(
                            HEADER_URL,
                          ),
                          fit: BoxFit.cover)
                      : DecorationImage(
                          image: CachedNetworkImageProvider(
                            list.data.friendApplicationList[i].faceUrl,
                          ),
                          fit: BoxFit.cover)),
              child: Text("")),
          title: Text(
            list.data.friendApplicationList[i].nickname ?? "",
            style: TextStyle(fontSize: sp(15)),
          ),
          subtitle: Text(
            list.data.friendApplicationList[i].addWording ?? "",
            style: TextStyle(
                fontSize: sp(12), color: ZdColor.rgba(153, 153, 153, 1)),
          ),
          trailing: InkWell(
            onTap: () {
              TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
                  .acceptFriendApplication(
                      responseType: 1,
                      type: 1,
                      userID: list.data.friendApplicationList[i].userID)
                  .then((value) async {
                TencentImSDKPlugin.v2TIMManager
                    .getLoginUser()
                    .then((value) async {
                  await TencenNewFirendsDao.addInfo(
                      list.data.friendApplicationList[i].addWording,
                      list.data.friendApplicationList[i].addTime.toString(),
                      DateTime.now().millisecondsSinceEpoch.toString(),
                      "1",
                      list.data.friendApplicationList[i].userID,
                      value.data);
                });

                await _getFriendsApp();
              });
            },
            child: Container(
              alignment: Alignment.center,
              width: 50.w,
              height: 30,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: ZdColor.rgba(0, 220, 169, 1)),
              child: Text(
                "接受",
                style: TextStyle(fontSize: 12.sp, color: Colors.white),
              ),
            ),
          ),
          onTap: () {
            Get.to(() => UserAddInfoPage(
                  friendApplicationEntity: list.data.friendApplicationList[i],
                  userEntity: friendInfoResult[i].friendInfo.userProfile,
                )).then((value) async {
              await _getFriendsApp();
            });
            // print(userEntity.userID);

            //
            // LogUtil.e("onItemClick : $model");
            // Utils.showSnackBar(context, 'onItemClick : ${model.name}');
          },
        ));
        dataList.add(Divider(
          height: 1,
          indent: width(65),
          endIndent: width(15),
        ));
      }
    }

    dataList.add(Container(
      margin: EdgeInsets.only(top: 14),
      padding: EdgeInsets.only(left: 15.w),
      height: 30,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: ZdColor.rgba(241, 241, 241, 1),
      ),
      child: Text(
        "已处理",
        style:
            TextStyle(fontSize: sp(12), color: ZdColor.rgba(153, 153, 153, 1)),
      ),
    ));

    FriendApplist friendApplist =
        await TencenNewFirendsDao.getFriednsApplist(widget.userId);
    if (friendApplist.resultCode == 1) {
      if (friendApplist.data != null && friendApplist.data.length > 0) {
        for (int i = 0; i < friendApplist.data.length; i++) {
          V2TimValueCallback<List<V2TimFriendInfoResult>> v2list =
              await TencentImSDKPlugin.v2TIMManager
                  .getFriendshipManager()
                  .getFriendsInfo(userIDList: [friendApplist.data[i].toUserId]);

          if (friendApplist.data[i].status == "1") {
            dataList.add(friendapp(v2list, friendApplist, i, 1));
            dataList.add(Divider(
              height: 1,
              indent: width(65),
              endIndent: width(15),
            ));
          } else if (friendApplist.data[i].status == "2") {
            dataList.add(friendapp(v2list, friendApplist, i, 2));
            dataList.add(Divider(
              height: 1,
              indent: width(65),
              endIndent: width(15),
            ));
          } else if (friendApplist.data[i].status == '3') {
            dataList.add(friendapp(v2list, friendApplist, i, 3));
            dataList.add(Divider(
              height: 1,
              indent: width(65),
              endIndent: width(15),
            ));
          }
        }
      }
    }
    setState(() {});
  }

  ListTile friendapp(V2TimValueCallback<List<V2TimFriendInfoResult>> v2list,
      FriendApplist friendApplist, int i, int type) {
    return ListTile(
      leading: Container(
          height: width(40),
          width: width(40),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6),
              color: Colors.greenAccent,
              image: v2list.data[0].friendInfo.userProfile.faceUrl == null
                  ? DecorationImage(
                      image: CachedNetworkImageProvider(
                        HEADER_URL,
                      ),
                      fit: BoxFit.cover)
                  : DecorationImage(
                      image: CachedNetworkImageProvider(
                        v2list.data[0].friendInfo.userProfile.faceUrl,
                      ),
                      fit: BoxFit.cover)),
          child: Text("")),
      title: Text(
        v2list.data[0].friendInfo.userProfile.nickName ?? "",
        style: TextStyle(fontSize: sp(15)),
      ),
      subtitle: Text(
        friendApplist.data[i].content == 'null'
            ? "对方申请添加您为好友"
            : friendApplist.data[i].content,
        style:
            TextStyle(fontSize: sp(12), color: ZdColor.rgba(153, 153, 153, 1)),
      ),
      trailing: Container(
        alignment: Alignment.center,
        width: 50.w,
        height: 30,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
        ),
        child: Text(
          type == 1
              ? type == 3
                  ? "已过期"
                  : '已同意'
              : "已拒绝",
          style: TextStyle(
            fontSize: 12.sp,
          ),
        ),
      ),
      onTap: () {
        if (type == 2 || type == 3) {
          Get.to(() => UserAddInfoPage(
                friendApplicationEntity: list.data.friendApplicationList[i],
                userEntity: friendInfoResult[i].friendInfo.userProfile,
                type: 2,
              )).then((value) async {
            await _getFriendsApp();
          });
        }
        // print(userEntity.userID);

        //
        // LogUtil.e("onItemClick : $model");
        // Utils.showSnackBar(context, 'onItemClick : ${model.name}');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onHorizontalDragUpdate: (details) {
        print("============${details.globalPosition.dx}");
        // if (details.globalPosition.dx > 60 && details.globalPosition.dx < 120) {
        //   Navigator.pushAndRemoveUntil(
        //       context,
        //       FadeRoute(HomePage(
        //         pageIndex: 1,
        //       )),
        //       (route) => false);
        // }
      },
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            onPressed: () => Get.back(),
            icon: Icon(Icons.arrow_back_ios_rounded),
          ),
          elevation: 0,
          title: Text(
            "添加好友",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(16), color: Colors.black),
          ),
          centerTitle: true,
        ),
        body: ListView(children: dataList),
      ),
    );
  }
}
